import numpy as np
import cv2
from matplotlib import pyplot as plt

# built-in modules
import sys

# local modules
import video

import logging


def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    # handler = logging.FileHandler('log.txt', mode='w')
    # handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger


logger = setup_custom_logger('app')

if __name__ == '__main__':
    hsv_map = np.zeros((180, 256, 3), np.uint8)
    h, s = np.indices(hsv_map.shape[:2])
    hsv_map[:, :, 0] = h
    hsv_map[:, :, 1] = s
    hsv_map[:, :, 2] = 255
    hsv_map = cv2.cvtColor(hsv_map, cv2.COLOR_HSV2RGB)
    # cv2.imshow('hsv_map', hsv_map)
    # plt.imshow(hsv_map), plt.show()
    # cv2.namedWindow('hist', 0)
    # hist_scale = 10
    #
    #
    # def set_scale(val):
    #     global hist_scale
    #     hist_scale = val
    #
    #
    # cv2.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)

    # try:
    #     fn = sys.argv[1]
    # except:
    #     fn = 0
    # cam = video.create_capture(fn, fallback='synth:bg=/home/liusen/IdeaWorkspace/wechat-jump/mijing/00000.png:class=chess:noise=0.05')
    # cam = video.create_capture(fn, fallback='synth:bg=/home/liusen/IdeaWorkspace/wechat-jump/mijing/00000.png')

    # path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/00000.png'
    path = '/home/liusen/IdeaWorkspace/wechat-jump/mijing/20180806.png'

    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # img = img[607:650, 535:744] # 确定按钮
    img = img[179:249, 566:716]

    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)

    FILTER_MIN = np.array([100, 50, 130], np.uint8)
    FILTER_MAX = np.array([120, 70, 255], np.uint8)
    frame_threshed = cv2.inRange(hsv, FILTER_MIN, FILTER_MAX)
    hsv = cv2.bitwise_or(hsv, hsv, mask=frame_threshed)

    img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
    img[np.where((img != [0, 0, 0]).all(axis=2))] = [255, 255, 255]

    template = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img = cv2.imread(path)
    # img = img[152:353, 178:1118]

    # hsv2 = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    # frame_threshed = cv2.inRange(hsv2, FILTER_MIN, FILTER_MAX)
    # hsv2 = cv2.bitwise_or(hsv2, hsv2, mask=frame_threshed)
    #
    # hsv2 = cv2.cvtColor(hsv2, cv2.COLOR_HSV2RGB)
    # hsv2[np.where((hsv2 != [0, 0, 0]).all(axis=2))] = [255, 255, 255]
    # img2 = cv2.cvtColor(hsv2, cv2.COLOR_RGB2GRAY)
    #
    # res = cv2.matchTemplate(img2, template, cv2.TM_CCOEFF_NORMED)
    # logger.debug("value : {}".format(res[0][0]))
    #
    # plt.imshow(hsv2)
    # plt.show()
    # # img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # # cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing3/sarcastic_creature.png', img)
    # sys.exit()


    # while True:
    #     dark = hsv[..., 2] < 32
    #     hsv[dark] = 0
    #     h = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
    #
    #     h = np.clip(h * 0.005 * hist_scale, 0, 1)
    #     vis = hsv_map * h[:, :, np.newaxis] / 255.0
    #     cv2.imshow('hist', vis)
    #
    #     ch = cv2.waitKey(1)
    #     if ch == 27:
    #         break
    #
    # cv2.destroyAllWindows()

    # dark = hsv[..., 2] < 32
    # logger.debug("---------dark-------------")
    # logger.debug(dark)
    # hsv[dark] = 0
    h = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
    # logger.debug(h)
    h = np.clip(h * 0.005 * 32, 0, 1)
    vis = hsv_map * h[:, :, np.newaxis] / 255.0
    # logger.debug("---------vis-------------")
    # logger.debug(vis)

    plt.subplot(221), plt.imshow(hsv_map)
    plt.subplot(222), plt.imshow(vis)

    # hsv2 = hsv
    # a = hsv2[..., 0] < 200
    # hsv2[a] = 0
    # a = hsv2[..., 0] > 220
    # hsv2[a] = 0
    # logger.debug(a)
    # a = hsv2[..., 0] >= 1
    # hsv2[a] = 255
    # a = hsv2[..., 0]

    # a = hsv
    # a = cv2.cvtColor(a, cv2.COLOR_GRAY2RGB)
    # logger.debug(a)
    plt.subplot(223), plt.imshow(hsv)

    # unique, counts = np.unique(a, return_counts=True)
    # print(dict(zip(unique, counts)))

    h2 = cv2.calcHist([hsv], [0], None, [180], [0, 180])
    # logger.debug("---------h2-------------")
    # logger.debug(h2)
    # logger.debug(h2[80:120])

    plt.subplot(224), plt.plot(h2, color='b'), plt.xlim([0, 180])

    plt.show()
